<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Account Class
 *
 * @category  Home
 */
class AccountAction extends HomeAction
{

	
	//初始化
	public function _initialize()
	{
		parent::_initialize();
		import('ORG.Net.Http');
	}

	
	//------------------------------ 各类认证绑定 ------------------------------

	//facebook账号认证
	public function facebookAuth()
	{
		vendor('Facebook.Facebook');
	}


	//twitter账号认证
	public function twitterAuth()
	{
		
		$Account = D('UserAccount');

		$param = unserialize(kg_base64($_GET['param'], 'decode'));
    	$map = array('hash' => kg_crc32($param['identifier']));
    	$account = $Account->where($map)->find();

    	if (!empty($account))
    	{
    		$userID = $account['user_id'];
    		$this->loginAuthCallback($userID);
    	}
    	else
    	{
        	cookie('account', $param);
        	$this->redirect('Account/register', array('type'=>'external'));
    	}
	}


    //openid帐号认证
    public function openidAuth()
    {
    	
		$Account = M('UserAccount');

		$param = unserialize(kg_base64($_GET['param'], 'decode'));
    	$map = array('hash' => kg_crc32($param['identifier']));
    	$account = $Account->where($map)->find();

    	if (!empty($account))
    	{
    		$userID = $account['user_id'];
    		$this->loginAuthCallback($userID);
    	}
    	else
    	{
            cookie('account', $param);
    	    $this->redirect('Account/register', array('type'=>'external'));
    	}
    }


    //本地账号认证
    public function localAuth()
    {

    	$captcha  = require_captcha_when('login');
    	
    	$account  = trim($_POST['account']);
    	$password = trim($_POST['password']);

    	$loginPerms = $this->_User->checkLogin();
    	if (!$loginPerms)
    	{
    	    $message = sprintf(L('flood_login_attempts'), $this->_global['max_login_attempts']);
    		$this->error($message);
    	}

    	if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
		{
		    $this->_User->logFailedLogin($loginPerms);
			$this->error(L('captcha_incorrect'));
		}

    	$where = array();
    	if (false !== strpos($account, '@'))
    	{
    		$where['email'] = $account;
    	}
    	else
    	{
    		$where['username'] = $account;
    	}

    	$user = $this->_User->where($where)->find();
    	if (!empty($user))
    	{
    	    if (kg_password_encrypt($_POST['password'], $user['salt']) != $user['password'])
    	    {
    	        $this->_User->logFailedLogin($loginPerms);
    	    	$this->error(L('password_incorrect'));
    	    }
    	    else
    	    {
    		    $this->loginAuthCallback($user['user_id']);
    	    }
    	}
    	else
    	{
			$this->_User->logFailedLogin($loginPerms);
    	 	$this->error(L('username_incorrect'));
    	}
    }
    
	
    //------------------------------ 各类认证绑定结束 ------------------------------
    
	
	//用户登录
    public function login()
    {
    	
        cookie('http_referer', $_SERVER['HTTP_REFERER']);

        if (isset($_GET['inviter']))
        {
        	cookie('inviter_id', $_GET['inviter']);
        }

    	if (isset($_POST['add_provider']))
    	{
    		cookie('add_provider', 1);
    	}
    	else
    	{
	    	if (!empty($this->_user['user_id']))
	    	{
	    		redirect($this->_global['site_url']);
	    	}
    	}

    	$captcha = require_captcha_when('login');
    	$this->assign('captcha', $captcha);
    	$this->display();
    }


    //用户登出
    public function logout()
    {
    	
        $Session = D('UserSession');
        $Session->unsetSession($this->_user['user_id']);

    	cookie('user', NULL);
    	cookie('session_id', NULL);
    	
    	$this->assign('jumpUrl', $this->_global['site_url']);
    	$this->success(L('logout_ok'));
    }


    //登录认证后续回调处理
    protected function loginAuthCallback($userID)
    {
    	
        $Activity = M('Activity');
        $Session  = M('UserSession');

        //拒绝帐号同一时间多人使用
        $map = array('user_id' => $userID);
        $count = $Session->where($map)->count();
        if ($count > 0)
        {
            $this->error(L('account_using_by_others'));
        }

    	//累加用户登录积分
		$today = strtotime(date('y-m-d'));
		$tomorrow = $today + 86400;
		$activityType = 'login';
		$map = array(
			'user_id'     => $userID,
			'type'        => $activityType,
			'create_time' => array('between', array($today, $tomorrow)),
		);
		$count = $Activity->where($map)->count();
		if (empty($count))
		{
			$points = get_activity_points($activityType);
			$this->_User->logActivity($userID, $activityType, $points, 0);
			$this->_User->updatePointCount($userID, $points);
		}

        $httpReferer = cookie('http_referer');
        cookie('session_id', NULL);
        cookie('http_referer', NULL);
        $this->_User->cookieUser($userID);
        
        $jumpUrl = !empty($httpReferer) ? $httpReferer : $this->_global['site_url'];
        $this->assign('jumpUrl', $jumpUrl);
        $this->success(L('login_ok'));
    }
   

    //绑定账号
    public function doAddProvider()
    {
    	
    	$Account = M('UserAccount');

    	$account = unserialize(kg_base64($_GET['param'], 'decode'));
    	$hash = kg_crc32($account['identifier']);
    	$map = array('hash' => $hash);
    	$result = $Account->where($map)->find();

    	if (empty($result) && !empty($this->_user))
    	{
    		$data = array(
    			'user_id'     => $this->_user['user_id'],
    			'hash'        => $hash,
    			'provider'    => $account['provider'],
    			'identifier'  => $account['identifier'],
    			'create_time' => time(),
    		);
    		$Account->add($data);
    	}

    	$url= format_user_url($this->_user['user_id'], $this->_user['username']);
    	redirect($url);
    }


    //解除绑定账号
    public function delProvider()
    {
    	
        $Account = M('UserAccount');

        $hash = $_GET['hash'];
    	$account = $Account->find($hash);
    	if ($account['user_id'] != $this->_user['user_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	$map = array('user_id' => $this->_user['user_id']);
    	$count = $Account->where($map)->count();
    	if ($count > 1)
    	{
    	    $where = array('hash' => $hash);
    		$Account->where($where)->delete();
    	}

    	$url= format_user_url($this->_user['user_id'], $this->_user['username']);
    	redirect($url);
    }


    //确认激活账号
    public function confirmAccount()
    {
    	
    	$userID = kg_auth_code($_GET['auth'], 'decode');
    	$user = $this->_User->find($userID);

    	if (empty($user))
    	{
    		$this->error(L('account_confirm_link_invalid'));
    	}
    	elseif (4 != $user['user_group'])
    	{
    		redirect($this->_global['site_url']);
    	}
    	else
    	{
    		$where = array('user_id' => $userID);
    		$this->_User->where($where)->setField('user_group', 7);
    		$this->_User->autoUpgradeLevel($userID);

			//奖励邀请人以及加关注
			if (!empty($user['inviter_id']))
    		{
    		    $Dao = D('UserFollow');
                $Dao->addFollow($user['user_id'], $user['inviter_id']);
    		    $this->_User->rewardInviter($user['inviter_id']);
    		}

    		$jumpUrl = format_user_url($user['user_id'], $user['username']);
    		$this->assign('jumpUrl', $jumpUrl);
			$this->success(L('account_confirmed'));
    	}
    }


    //编辑邮箱
    public function editEmail()
    {
    		
    	$email  = trim($_POST['email']);
    	$userID = intval($_POST['uid']);
    	$user = $this->_User->find($userID);
    
    	if ($userID != $this->_user['user_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
		
		$emailValidated = is_valid_email($email);
		if (true !== $emailValidated)
		{
			$this->error(L($emailValidated));
		}
		
    	//邮件地址重新验证
		if ('by_user' == $this->_global['require_activation'])
		{
			$requestUrl = get_site_domain() . U('Notification/validateEmail', array('uid' => $user['user_id'], 'email' => $email));
			Http::async_request($requestUrl);
			$message = L('email_require_validation');
		}
		else
		{
			$map = array('user_id' => $userID);
		    $this->_User->where($map)->setField('email', $email);
		    $message = L('user_email_edited');
		}
		$this->success($message);
    }
    
    
    //邮箱地址验证
    public function validateEmail()
    {
    	
    	list($userID, $email) = explode("\t", kg_auth_code($_GET['auth'], 'decode'));
    	$user = $this->_User->find($userID);

    	if (empty($user))
    	{
    		$this->error(L('email_validation_link_invalid'));
    	}
    	else
    	{
    		$map = array('user_id' => $userID);
    		$this->_User->where($map)->setField('email', $email);
            
    		$jumpUrl = format_user_url($user['user_id'], $user['username']);
    		$this->assign('jumpUrl', $jumpUrl);
    		$this->success(L('email_validated'));
    	}
    }


    //忘记密码
    public function forgetPassword()
    {
    	
        $captcha = require_captcha_when('email');

        if (!empty($this->_user['user_id']))
        {
        	redirect($this->_global['site_url']);	
        }
        
    	if ($this->isPost())
    	{
			$map = array(
                'username' => $_POST['username'],
			    'email'    => $_POST['email'],
			);
			$user = $this->_User->where($map)->find();
			if (empty($user))
			{
				$this->error(L('no_email_user'));
			}

			if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
			{
				$this->error(L('captcha_incorrect'));
			}

			$Mailer = A('Mailer');
			$result = $Mailer->resetPassword($user['user_id']);

			if ($result)
			{
				$this->assign('waitSecond', 60);
				$this->assign('jumpUrl', $this->_global['site_url']);
				$this->success(L('send_pwd_reset_email_ok'));
			}
			else
			{
				$this->error(L('send_email_failed'));
			}
		}
		else
		{
		    $seo = array(
		      'title' => L('forget_password'),
		      'keywords' => '',
		      'description' => '',
		    );

		    $this->assign('seo', $seo);
		    $this->assign('captcha', $captcha);
		    $html = $this->fetch();
		    exit($html);
        }
    }


    //重置密码
    public function resetPassword()
    {
    	
    	$cookie = cookie('password_reset_link');
    	list($userID, $password, $expire) = explode("\t", kg_auth_code($_GET['auth'], 'decode'));
    	$user = $this->_User->find($userID);
    	
    	$this->assign('jumpUrl', $this->_global['site_url']);
    	
    	if (empty($user))
    	{
    		$this->error(L('password_reset_link_invalid'));
    	}

    	if ($expire < time() || empty($cookie))
    	{
    		$this->error(L('password_reset_link_expired'));
    	}

    	$salt = kg_password_salt();
    	$password = kg_password_encrypt($password, $salt);
    	$data = array(
    	   'salt' => $salt,
    	   'password' => $password,
    	);
    	$map = array('user_id' => $userID);
    	$this->_User->where($map)->save($data);

    	cookie('pwd_reset_link', NULL);

    	$this->assign('jumpUrl', U('Account/login'));
    	$this->assign('waitSecond', 60);
    	$this->success(L('password_reseted'));
    }


    //创建(修改)本地账号密码
    public function editPassword()
    {
    	
    	$userID = intval($_POST['uid']);
    	$user = $this->_User->find($userID);

    	//检查用户权限
    	if ($userID != $this->_user['user_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
		
		$passwordValidated = is_valid_password($_POST['password']);
		if (true !== $passwordValidated)
		{
			$this->error(L($passwordValidated));
		}
		
		if ($_POST['password'] != $_POST['repassword'])
		{
			$this->error(L('password_not_match'));
		}
    		
    	//修改密码
    	$currentPassword = kg_password_encrypt($_POST['current_password'], $user['salt']);
		if (isset($_POST['current_password']) && $currentPassword != $user['password'])
		{
			$this->error(L('password_current_incorrect'));
		}

		$salt = kg_password_salt();
		$password = kg_password_encrypt($_POST['password'], $salt);
		$data = array(
		    'salt' => $salt,
			'password' => $password,
		);
		$this->_User->where('user_id='.$userID)->save($data);

		$jumpUrl = format_user_url($user['user_id'], $user['username']);
		$this->assign('jumpUrl', $jumpUrl);
		$this->success(L('user_profile_updated'));
    }

}
//End Class

/* End of file AccountAction.class.php */
/* Location: ./App/Lib/Action/Home/AccountAction.class.php */